package zhc.app.base.aop.slog;


import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by wizzer on 2016/6/22.
 */
@IocBean(create="init", depose="close")
public class SLogService{

    private static final Log log = Logs.get();

    ExecutorService es;

    @Inject
    protected Dao dao;

    public void async(final Sys_log syslog) {
        es.execute(new Runnable() {
            public void run() {
                try {
                    dao.fastInsert(syslog);
                } catch (Exception e) {
                    log.error("insert syslog sync fail", e);
                }
            }
        });
    }

    public void sync(Sys_log syslog) {
        try {
            dao.fastInsert(syslog);
        } catch (Throwable e) {
            log.error("insert syslog sync fail", e);
        }
    }

    public void init() {
        int c = Runtime.getRuntime().availableProcessors();
        es = Executors.newFixedThreadPool(c);
    }

    public void close() throws InterruptedException {
        if (es != null && !es.isShutdown()) {
            es.shutdown();
            es.awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}